package com.coolingme.serializable04;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * 使用序列化破坏单例模式
 *
 * @author wangyue
 * @date 2020/9/29 14:05
 */
public class SerializableBreakSingletonTest {

    public static void main(String[] args) {
        // 获取需要写入的单例对象
        LazySerializableSingleton instance1 = LazySerializableSingleton.getInstance();
        // 序列化读取的单例对象
        LazySerializableSingleton instance2;
        String property = System.getProperty("user.dir");
        String objUrl = property + "\\pattern-02-singleton\\src\\main\\java\\com\\coolingme\\serializable04\\Serializable.obj";
        System.out.println("序列化对象地址：" + objUrl);
        try {
            // 写
            FileOutputStream fos = new FileOutputStream(objUrl);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(instance1);
            oos.flush();
            oos.close();

            // 读
            FileInputStream fis = new FileInputStream(objUrl);
            ObjectInputStream ois = new ObjectInputStream(fis);
            instance2 = (LazySerializableSingleton) ois.readObject();
            ois.close();

            System.out.println(instance1);
            System.out.println(instance2);
            // true
            System.out.println(instance1 == instance2);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
